/***
 * 脚本依赖;
 * common.js
 * ejs.js
 * $,jQuery
 *
 */
(function ($) {
    var $Report = {
        tableSelect: function ($report, destroyBtn, createBtn, options) {
            $report.find('tbody tr').unbind('click').click(function () {
                if ($(this).text() && $(this).text().indexOf('没有找到符合查询条件的数据!') > -1) {
                    return;
                }
                if ($(this).hasClass('active')) {
                    destroyBtn && destroyBtn();
                    $(this).removeClass('active').find('td:first-child input[type=checkbox]').attr('checked', false).prop('checked', false);
                } else {
                    createBtn && createBtn(this);
                    var $checkbox = $(this).addClass('active').find('td:first-child input[type=checkbox]');
                    if ($checkbox.length) {
                        $checkbox.attr('checked', true).prop('checked', true);
                        if (!options.multiSelect) { // 单选
                            $checkbox.closest('tr').siblings('tr').removeClass('active').find('td:first-child input[type=checkbox]').attr('checked', false).prop('checked', false);
                        }
                    } else {
                        $(this).addClass('active');
                        if (!options.multiSelect) { // 单选
                            $(this).closest('tr').siblings('tr').removeClass('active').find('td:first-child input[type=checkbox]').attr('checked', false).prop('checked', false);
                        }
                    }

                }
            })
        },

        initThead: function () {
            var $tr_ = $('<tr></tr>');
            options.fields.forEach(function (item, index1) {

                if (index1 == 0) {

                    if (options.seqNum) {
                        $tr_.append($('<th>序号</th>').css({width: 35}));
                    }
                }
                var $th = $('<th>' + item.label + '</th>');
                $tr_.append($th);
            });

        },
        /***
         * 初始化搜索框
         */
        initSearch: function (options) {
            if ($('input.search').length) {
                return false;
            }
            //basic search
            var $searchType = $('<div class="input-group-btn"></div>'),
                $searchTypeDown = $('<ul class="dropdown-menu" role="menu"></ul>'),
                $searchTypeLabel = $('<button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown" aria-expanded="false">单位名称 <span class="caret"></span></button>'),
                $searchInput = $('<input type="text" class="form-control search" data-toggle="autocomplete"' +
                    ' placeholder="请输入...">'),
                $searchBtn = $('<span class="input-group-btn"><button class="btn btn-primary search-btn" data-loading-text="查询中..." type="button">查询</button></span>'),
                $searchCtner = $('<div class="input-group pull-left" style="width: 250px;"></div>');
            var $searchSenior = $('<div class="search-senior"></div>'),
                $searchFormInline = $('<div class="form-inline"></div>'),
                length = 0;
            options.fields.forEach(function (item, index) {
                if (item.enableSearch) {
                    length++;
                    var $item = $('<li><a href="#">' + item.label + '</a></li>');
                    var $seniorItem = '';
                    if (item.dateRange) { //日期范围搜索
                        $seniorItem = $('<div class="form-group input-daterange" data-toggle="datepicker" data-date-start-date="' + (item.start || '2017-03-01') + '"' +
                            ' data-date-end-date="' + ((item.end || moment(Date.now()).format('YYYY-MM-DD'))) + '"><label class="sr-only">' + item.label + ':</label>' +
                            '<input type="text" name="' + item.name + 'Start" data-date-size="small" readonly="readonly" class="form-control input-date"' +
                            ' placeholder="' + item.label + '开始日期"' +
                            ' style="width: 125px;">-<input  name="' + item.name + 'End"  readonly="readonly"  data-date-size="small" type="text" class="form-control input-date" ' +
                            ' style="width: 125px;" placeholder="' + item.label + '结束日期" >');
                    } else {
                        $seniorItem = $('<div class="form-group"><label class="sr-only">' + item.label + '：</label>' +
                            '<input type="text" class="form-control" name="' + item.name + '" placeholder="' + item.label + '">&nbsp;</div>');
                        $seniorItem = $('<div class="form-group ><label class="sr-only">' + item.label + '：</label>' +
                            '<input type="text" class="form-control" name="' + item.name + '" placeholder="' + item.label + '">&nbsp;</div>');
                    }
                    $item.data('json', item);
                    $searchTypeDown.append($item);
                    $searchFormInline.append($seniorItem.css({marginBottom: '12px'}));
                    $item.unbind('click').click(function () {
                        var $data = $(this).data('json');
                        $searchTypeLabel.html($data.label + ' <span class="caret"></span>').data('json', $data);
                    });
                    if (!$searchTypeLabel.data('json')) { // 未初始化
                        $searchTypeLabel.html(item.label + ' <span class="caret"></span>').data('json', item)
                    }
                }

                if (item.enableFilter) {
                    length++;
                    var $item = $('<li><a href="#">' + item.label + '</a></li>');
                    var $seniorItem = $('<div class="form-group"><label class="sr-only">' + item.label + '：</label>' +
                        '<select type="text" class="form-control" name="' + item.name + '" placeholder="' + item.label + '">' +
                        item.filters.map(function (item) {
                            return '<option value="' + item.value + '">' + item.label + '</option>';
                        }).join('') +
                        '</select></div>');

                    $item.data('json', item);
                    $searchTypeDown.append($item);
                    $searchFormInline.append($seniorItem.css({marginBottom: '12px'}));
                    if (item.multi) {
                        $seniorItem.find('select').attr("multiple", "multiple").css({marginRight:'5px'})
                            .multiselect($.extend(MULTI_SETTING, {
                            onDropdownHide: function (event) {
                            },
                            onChange: function (option, selected) {
                            },
                        }))

                    }
                }
            });
            if (length == 0)return;
            $searchType.append($searchTypeLabel).append($searchTypeDown);
            if (options.complexItems && options.showSearchComplex) {
                options.complexItems.forEach(function (item) {
                    var $seniorItem = '';
                    if (item.dateRange) { //日期范围搜索
                        $seniorItem = $('<div class="form-group input-daterange" data-toggle="datepicker" data-date-start-date="' + (item.start || '2017-03-01') + '"' +
                            ' data-date-end-date="' + ((item.end || moment(Date.now()).format('YYYY-MM-DD'))) + '"><label class="sr-only">' + item.label + ':</label>' +
                            '<input type="text" readonly="readonly" name="' + item.name + 'Start" data-date-size="small" class="form-control input-date"' +
                            ' placeholder="' + item.label + '开始日期"' +
                            ' style="width: 125px;">-<input  readonly="readonly"  name="' + item.name + 'End"  data-date-size="small" type="text" class="form-control input-date" ' +
                            ' style="width: 125px;" placeholder="' + item.label + '结束日期" >');
                    } else {
                        $seniorItem = $('<div class="form-group"><label class="sr-only">' + item.label + '：</label>' +
                            '<input type="text"  readonly="readonly" class="form-control" name="' + item.name + '" placeholder="' + item.label + '">&nbsp;</div>');
                        $seniorItem = $('<div class="form-group ><label class="sr-only">' + item.label + '：</label>' +
                            '<input type="text"  readonly="readonly" class="form-control" name="' + item.name + '" placeholder="' + item.label + '">&nbsp;</div>');
                    }
                    $searchFormInline.append($seniorItem.css({marginBottom: '12px'}));
                })
            }
            $searchBtn.unbind('click').click(function () { // 单项搜索
                var $data = $searchTypeLabel.data('json');
                var obj = {};
                var $lis = $(this).closest('.input-group').find('li');
                $lis.each(function () {
                    var $json = $(this).data('json');
                    obj[$json.name] = ""; // 单项搜索时，过滤非当前项条件干扰
                });
                obj[$data.name] = $searchInput.val();
                obj.page = 1;
                options.search && options.search(obj)
            });
            $searchCtner.append($searchType).append($searchInput).append($searchBtn);
            var $searchSwitch = $('<a class="search-switch pull-left">高级搜索</a>'),
                $search = $('<button type="submit" class="btn btn-primary">搜索</button>'),
                $export = $('<button class="btn btn-primary export">导出</button>');
            $searchFormInline.append($search.css({marginBottom: '12px'}));
            $search.unbind('click').click(function () { // 高级搜索
                var search = {};
                $(this).siblings('.form-group').find('input').each(function (index, item) {
                    search[item.name] = item.value;
                });
                options.search && options.search(search)
            });
            $searchSenior.hide();
            $searchSenior.append($searchFormInline);
            $searchSwitch.unbind('click').click(function () {
                if ($(this).text().indexOf('高级') > -1) {
                    $(this).text('普通搜索');
                    $searchCtner.hide();
                    $searchSenior.show();
                    $searchSenior.find('input[name=' + $searchTypeLabel.data('json')['name'] + ']').val($searchInput.val())
                } else {
                    $searchCtner.show();
                    $searchSenior.hide();
                    $searchInput.val($searchSenior.find('input[name=' + $searchTypeLabel.data('json')['name'] + ']').val());
                    // $searchSenior.find('input[name='+$searchTypeLabel.data('json')['name']+']').val($searchInput.val())
                    $(this).text('高级搜索')
                }
            });
            if(options.export){
                var date = new Date();
                $export.unbind('click').click(function () {
                    if(options.search){
                        var search = {};
                        $(this).siblings('.form-group').find('input,select').each(function (index, item) {
                            search[item.name] = item.value;
                        });
                        generateExportUrl(options.search({},true,true));
                    }
                });
                $searchFormInline.append($export.css({marginBottom: '12px'}));
            }
            $searchSenior.css({padding: '12px 12px 0'});
            $searchFormInline.css({borderBottom: '1px solid #f4f4f4', paddingBottom: '0px'})
            $(options.toolbar).find('.pull-right').append($searchCtner);
            if (length > 1 || options.showSearchComplex) {
                $(options.toolbar).find('.pull-right').append($searchSwitch);
                if (options.showSearchComplex) {
                    $searchSwitch.click().hide();
                }
            }

            $searchSenior.insertBefore($(options.toolbar).closest('.panel-body'));


        },
        initTbody: function (options) {

        },
        init: function (options) {
            var $report = $(this);
            initSubPageScroll();
            var $tr_ = $('<tr></tr>'),
                $thead = $('<thead></thead>'),
                $tbody = $('<tbody></tbody>');
            // if (options.data.length == 0) {
            //     $report.html(noData(1));
            // }
            var $trTotal_ = $('<tr></tr>'), total_ = {}, remain = 0;
            if (options.data.length == 0) {
                var $tr = $('<tr></tr>');
                options.fields.forEach(function (item, index1) {
                    var $td = $('<td  style="' + (item.style || '') + '" ></td>');
                    if (item.total) {
                        // total_[item.name] =0;
                        total_[item.name] = item.initValue || 0;
                        if (item.name == 'remain') {
                            remain += item.initValue;
                        }
                        if (total_[item.name]) {
                            total_[item.name] = floatTool.add(total_[item.name] || 0, 0);
                        } else {
                            total_[item.name] = 0;
                        }
                    }
                    if (item.name == 'remain') {
                        var remainTmpl = floatTool.subtract(0, 0);
                        remain = floatTool.add(remain, remainTmpl);
                        $td.html(remain);
                    }
                    if (index1 == 0) {
                        if (options.seqNum) {
                            $tr.append($('<td></td>'));
                        }
                    }
                    if (index1 == 0) {
                        if (options.seqNum) {
                            $tr_.append($('<th>序号</th>').css({width: 40, marginRight: '7px', 'fontSize': '10px'}));
                        }
                        $trTotal_.append($('<td>合计</td>'));
                    }
                    if (item.total) { // 合计
                        $trTotal_.append('<td class="total-' + item.name + '"></td>')
                    } else {
                        $trTotal_.append('<td></td>')
                    }
                    var $th = $('<th>' + item.label + '</th>');
                    $th.addClass('custom-' + item.name);

                    $tr_.append($th);
                    $td.addClass('custom-' + item.name);
                    if ($('th.custom-' + item.name).length && $('th.custom-' + item.name).css('display') == 'none') {
                        $td.hide()
                    }
                    $tr.append($td)
                });
                $tbody.append($tr);
            } else {
                options.data.forEach(function (obj, index) {
                    var $tr = $('<tr></tr>');
                    options.fields.forEach(function (item, index1) {
                        var $td = $('<td  style="' + (item.style || '') + '" >' + (!!item.filter ? item.filter(obj) : ((obj[options.fields[index1].name] != 0) ? (obj[options.fields[index1].name] || '-') : obj[options.fields[index1].name])) + '</td>');
                        if (item.total) {
                            // total_[item.name] =0;
                            if (index == 0) {
                                total_[item.name] = item.initValue || 0;
                                if (item.name == 'remain') {
                                    remain += item.initValue;
                                }
                            }
                            if (total_[item.name]) {
                                total_[item.name] = floatTool.add(total_[item.name] || 0, item.filter(obj));
                            } else {
                                total_[item.name] = item.filter(obj);
                            }
                            if (item.name == 'numberReceiving') {
                                console.log(total_[item.name]);
                            }
                        }
                        if (item.name == 'remain') {
                            var remainTmpl = floatTool.subtract(options.fields[index1 - 2].filter(obj), options.fields[index1 - 1].filter(obj));
                            remain = floatTool.add(remain, remainTmpl);
                            $td.html(remain);
                        }
                        if (item.filterAsync) {
                            item.filterAsync(obj, $td);
                        }
                        if (index1 == 0) {
                            if (options.seqNum) {
                                $tr.append($('<td>' + (index + 1) + '</th>'));
                            }
                        }
                        if (index == 0) {
                            if (index1 == 0) {
                                if (options.seqNum) {
                                    $tr_.append($('<th>序号</th>').css({
                                        width: 40,
                                        marginRight: '7px',
                                        'fontSize': '10px'
                                    }));
                                }
                                $trTotal_.append($('<td>合计</td>'));
                            }
                            if (item.total) { // 合计
                                $trTotal_.append('<td class="total-' + item.name + '"></td>')
                            } else {
                                $trTotal_.append('<td></td>')
                            }
                            var $th = $('<th>' + item.label + '</th>');
                            $th.addClass('custom-' + item.name);
                            $tr_.append($th);
                        }
                        $td.addClass('custom-' + item.name);
                        if ($('th.custom-' + item.name).length && $('th.custom-' + item.name).css('display') == 'none') {
                            $td.hide()
                        }
                        $tr.append($td)
                    });
                    $tr.data('json', obj).attr('id', obj.id);
                    $tbody.append($tr);
                });
            }
            if (Object.keys(total_).length > 0) {
                // console.log(total_);
                Object.keys(total_).map(function (key) {
                    if (key == 'remain') {
                        $trTotal_.find('.total-remain').html(remain);
                        $tbody.append($trTotal_)
                    } else {
                        $trTotal_.find('.total-' + key).html(total_[key]);
                        $tbody.append($trTotal_)
                    }
                })
            }
            if ($report.hasClass('sticky-thead')) {
                return;
            }
            if ($report.data('$report') && $report.find('th').length) {
                $report.find('tbody').replaceWith($tbody);
            } else {
                $report.data('$report', $report);
                $Report.initSearch(options);
                if (options.onlyBody) {
                    $report.find('tbody').replaceWith(options.data.length == 0 ? noData($tr_.find('th:visible').length || 1) : $tbody);
                } else {
                    $report.html('').append($thead.append($tr_)).append($tbody);
                }

            }
            options.rendered && options.rendered();
        },
    };
    $.fn.$report = function (options) {
        var _default = {
            fields: []
        };
        options = $.extend({}, _default, options || {});
        if (!$.isArray(options.fields) || !options.fields.length) {
            throw new Error('option.field must be array and option.field.length must over 0 !')
        }
        return this.each(function () {
            $Report.init.call(this, options);
        })
    };
})(jQuery);


